package com.matchmealpha;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

public class ShareActivity extends Activity {

	protected static final int RETRIEVE_PHOTO_REQUEST_CODE = 1;
	protected static final int APPLY_FILTER_REQUEST_CODE = 2;
	protected static final int SHARE_SETTINGS_REQUEST_CODE = 3;
	protected static Bitmap CURRENT_IMAGE;
	protected static Bitmap ORIGINAL_IMAGE;

	protected boolean startCamera;
	protected int postid;
	protected int alertid;
	protected int[] image;
	protected int[] oImage;
	protected String sessionid;
	private String requester; 

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		

		Bundle bund = this.getIntent().getExtras();
		if (bund != null)
		{
			postid = bund.getInt("postid", -1);
		    alertid = bund.getInt("alertid", -1);
		    requester = bund.getString("requester");
		}
		else
		{
			requester = "";
			postid = -1;
		}
		
		SharedPreferences settings = getSharedPreferences(
				"matchme_preferences", 0);
		sessionid = settings.getString("sessionid", "");
		
		 final Boolean data = (Boolean) getLastNonConfigurationInstance();
		if(data != null)
		{
			startCamera = data.booleanValue();
		}else
		{
			startCamera = true;
		}
		
	}
	
	public Object onRetainNonConfigurationInstance() {
		return new Boolean(startCamera);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (RETRIEVE_PHOTO_REQUEST_CODE == requestCode) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "FAILED TO GET PIC", Toast.LENGTH_SHORT)
						.show();
				if(CURRENT_IMAGE != null)
				   CURRENT_IMAGE.recycle();
				if(ORIGINAL_IMAGE != null)
				   ORIGINAL_IMAGE.recycle();
				// startCamera=true;
				if (postid != -1) {
					finish();
				}
				startCamera = true;
				MatchMeTabWidget.myTabHost().setCurrentTab(1);

			} else if (resultCode == RESULT_OK) {
				oImage = data.getIntArrayExtra(CameraActivity.IMAGE_PIXELS);
				Intent i = new Intent(this, ApplyFilterActivity.class);
				//i.putExtra(CameraActivity.IMAGE_PIXELS, oImage);
				startActivityForResult(i, APPLY_FILTER_REQUEST_CODE);

				// Toast.makeText(this,
				// data.getStringExtra(CameraPreview.IMAGE_FILE_NAME),
				// Toast.LENGTH_SHORT).show();
			}
		} else if (APPLY_FILTER_REQUEST_CODE == requestCode) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode == RESULT_CANCELED) {
				Toast.makeText(this, "FAILED TO APPLY FILTERS",
						Toast.LENGTH_SHORT).show();
				if(CURRENT_IMAGE != null)
				    CURRENT_IMAGE.recycle();
				
				ORIGINAL_IMAGE.recycle();
				
				Intent i = new Intent(this, CameraActivity.class);
				startActivityForResult(i, RETRIEVE_PHOTO_REQUEST_CODE);

			} else if (resultCode == RESULT_OK) {
				Toast.makeText(this, "Starting PIC INFO!", Toast.LENGTH_SHORT)
						.show();
				//image = data.getIntArrayExtra(CameraActivity.IMAGE_PIXELS);
				Intent i = new Intent(this, ShareSettingActivity.class);
				i.putExtra("requester", this.requester);
				startActivityForResult(i, SHARE_SETTINGS_REQUEST_CODE);
			}
		} else if (SHARE_SETTINGS_REQUEST_CODE == requestCode) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode == RESULT_CANCELED) {
				 CURRENT_IMAGE.recycle();
				Intent i = new Intent(this, ApplyFilterActivity.class);
				//i.putExtra(CameraActivity.IMAGE_PIXELS, oImage);
				startActivityForResult(i, APPLY_FILTER_REQUEST_CODE);

			} else if (resultCode == RESULT_OK) {
				// Toast.makeText(this, "Starting PIC INFO!",
				// Toast.LENGTH_SHORT).show();
				// Intent i = new Intent(this, ShareSettingActivity.class);
				// i.putExtra(CameraActivity.IMAGE_PIXELS,
				// data.getIntArrayExtra(CameraActivity.IMAGE_PIXELS));
				// startActivityForResult(i, SHARE_SETTINGS_REQUEST_CODE);
				// startCamera = true;

				// /combine images
				String location = data
						.getStringExtra(ShareSettingActivity.MATCHME_LOCATION);
				String description = data
						.getStringExtra(ShareSettingActivity.MATCHME_DESCRIPTION);
				String requestee = data
						.getStringExtra(ShareSettingActivity.MATCHME_REQUESTEE);

				new PostTask().execute(location, description, requestee);
				startCamera = true;
				if (postid != -1) {
					
					finish();
				}else
				{
				   MatchMeTabWidget.myTabHost().setCurrentTab(1);
				}

				// MatchMeTabWidget.myTabHost().setCurrentTab(1);
			}
		}
	}

	protected void onStart() {
		super.onStart();
		if (startCamera) {
			startCamera = false;
			Intent i = new Intent(this, CameraActivity.class);
			startActivityForResult(i, RETRIEVE_PHOTO_REQUEST_CODE);
		}
	}

	private class PostTask extends AsyncTask<String, Void, Boolean> {

		protected Boolean doInBackground(String... data) {

			HttpRequest req = new HttpRequest(sessionid);
			String response;
			
			Post post = new Post();
			//post.setUserID2(data[2]);
			post.setBitMapImage(CURRENT_IMAGE);

			if (postid != -1) {
				// completing post
				
				byte[] byteArr = req.getByteArray(MatchMeTabWidget.MM_SERVER + "/get_image/" + postid);
				Bitmap otherImage = BitmapFactory.decodeByteArray (byteArr , 0, byteArr.length);
				
				Bitmap finalImage = FilterEffects.combineImages(otherImage, post.getBitMapImage());
				
				getPostImage(post, sessionid);
				post.setPostID(postid);
				post.setDescription2(data[1]);
				post.setLocation2(data[0]);
				post.setBitMapImage(finalImage);
				response = req.sendMultipartPost(2, post, alertid);

			} else {
				// creating post
				post.setDescription1(data[1]);
				post.setUserID2(data[2]);
				response = req.sendMultipartPost(1, post, -1);

			}
			
			if(MatchMeTabWidget.REQUEST_FAILURE.equals(response))
			{
				return true;
			}else
			{
				return false;
			}
		}

		protected void onPostExecute(Boolean result) {
			
			ShareActivity.CURRENT_IMAGE.recycle();
			ShareActivity.ORIGINAL_IMAGE.recycle();
			// loadingDialog.cancel();
//			if (result) {
//				if(postid !=-1)
//				{
//					finish();
//				}else
//				{
//					MatchMeTabWidget.myTabHost().setCurrentTab(1);
//				}
//			} else {
//				if(postid !=-1)
//				{
//				   MatchMeTabWidget.myTabHost().setCurrentTab(1);
//				}else
//				{
//					 MatchMeTabWidget.myTabHost().setCurrentTab(1);
//				}
//			}
			}
	}
	
	protected static void getPostImage(Post p, String mysessionid) {
		HttpRequest req2 = new HttpRequest(mysessionid);
		byte[] byteArr = req2.getByteArray(MatchMeTabWidget.MM_SERVER
				+ "/get_image/" + p.getPostID());
		p.setBitMapImage(BitmapFactory.decodeByteArray (byteArr , 0, byteArr.length));
	}
	
	
	protected static void getPostBitMapImage(Post p, String mysessionid) {
		HttpRequest req2 = new HttpRequest(mysessionid);
		byte[] byteArr = req2.getByteArray(MatchMeTabWidget.MM_SERVER
				+ "/get_image/" + p.getPostID());
		BitmapFactory.Options options=new BitmapFactory.Options();
		//options.inSampleSize = 8;
		Bitmap im = BitmapFactory.decodeByteArray (byteArr, 0, byteArr.length, options);
		p.setBitMapImage(im);
	}


}